package apiproxy

import (
    "fmt"
    "errors"
    "net/http"

    "github.com/grpc-ecosystem/grpc-gateway/runtime"
)

type RegisterFunc func(*runtime.ServeMux) error

type ApiProxyServer struct {
    HttpServer *http.Server
}

func mainHandlerFunc(serviceHandler *runtime.ServeMux) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        switch r.Method {
        case http.MethodHead:
            fmt.Fprintf(w, `{"status": "ok"}`)
        default:
			serviceHandler.ServeHTTP(w, r)
        }
	})
}

func NewApiProxyServer(proxyAddr string, registerFunc RegisterFunc) (*ApiProxyServer, error) {
    mux := runtime.NewServeMux()
    err := registerFunc(mux)
    if err != nil {
        return nil, err
    }

    httpServer := &http.Server{
        Addr:    proxyAddr,
        Handler: mainHandlerFunc(mux),
    }

    return &ApiProxyServer{HttpServer: httpServer}, nil
}

func (s *ApiProxyServer) Run(block bool) error {
    if s.HttpServer == nil {
        return errors.New("ApiProxyServer HttpServer is nil")
    }

    if block {
        s.HttpServer.ListenAndServe()
    } else {
        go s.HttpServer.ListenAndServe()
    }

    return nil
}
